// pages/message/chat/index.js
import {
  getChatMessagesApi,
  postChatSendApi,
  postChatReadApi
} from '../../../https/chat'
import {
  getInfoByIdApi,
} from '../../../https/user'
import {
  BASE_URL
} from '../../../constant/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    BASE_URL,
    receiverId: '', // 用户的id
    chatList: [], // 聊天记录
    myInfo: {}, // 自己的信息
    content: '', // 输入框内容
    scrollTo: "", // 滚动到底部
    isMenu: false, // 底部显示
    info: {} // 对方信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const docid = options.docid || 637676919323
    console.log(docid)
    this.setData({
      receiverId: docid
    })
    await this.getUserInfo()
    await this.getChatList()
    await this.postChatRead()
    this.scrollToBottom()
  },
  // 获取对方信息
  async getUserInfo() {
    const receiverId = this.data.receiverId
    const getRes = await getInfoByIdApi({
      id: receiverId
    })
    console.log(getRes)
    if (getRes.code == 200) {
      this.setData({
        info: getRes.data
      })
      wx.setNavigationBarTitle({
        title: getRes.data.nikeName,
      })
    }
  },
  // 对方消息标记已读
  async postChatRead() {
    const receiverId = this.data.receiverId
    const postRes = await postChatReadApi({
      receiverId
    })
    console.log(postRes)
    console.log('标记已读') 
  },
  // 获取聊天记录
  async getChatList() {
    const receiverId = this.data.receiverId
    console.log('获取聊天记录')
    const getRes = await getChatMessagesApi({
      receiverId
    })
    if (getRes.code == 200) {
      this.setData({
        chatList: getRes.data
      })
    }
  },
  // 切换输入框内容
  inputChange(e) {
    console.log(e)
    const value = e.detail.value
    this.setData({
      content: value
    })
  },
  // 切换底部状态
  toggleMenu() {
    this.setData({
      isMenu: !this.data.isMenu
    })
  },
  // 滚动到底部
  scrollToBottom(id) {
    if (!id) {
      id = 'last'
    }
    this.setData({
      scrollTo: `item${id}`
    });
  },
  // 发送消息
  async sendMessageBtn() {
    const content = this.data.content
    const receiverId = this.data.receiverId
    if (!content) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }
    const postRes = await postChatSendApi({
      receiverId,
      content
    })
    console.log(postRes)
    if (postRes.code == 200) {
      this.setData({
        content: ''
      })
      await this.getChatList()
      this.scrollToBottom()
    } else {

    }

  }
})